import { Body, Controller, Get, Ip, Param, Post, Req, Res, UseGuards } from "@nestjs/common";
import { AuthService } from "./auth.service";
import { Request, Response } from "express";
import { UserService } from "src/user/user.service";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { AuthGuard } from "@nestjs/passport";
import { CurrentUser } from "src/user/user.decorator";
import { UserSys } from "src/user/userSys.entity";
import { RoleService } from "src/role/role.service";
import { UserGuard } from "src/role/role.guard";
import { RoleEnum } from "src/role/role.enum";
import { SystemService } from "src/system/system.service";
import { AnnouncementService } from "src/announcement/announcement.service";



@Controller("api/auth")
@ApiTags("登录模块")
export class AuthController {
    constructor(
        private readonly authService: AuthService,
        private readonly userService: UserService,
        private readonly roleService: RoleService,
        private readonly systemService: SystemService,
        private readonly annService: AnnouncementService
    ) { }

    @Get("sign")
    @ApiOperation({ summary: "获取信息" })
    @UseGuards(AuthGuard("jwt"))
    public async sign(
        @CurrentUser() user: UserSys
    ) {
        const ann = await this.annService.get(user);
        return { ...user, password: null, router: this.roleService.getRoleRouter(user.role, user.dept?.deptRole), ann }
    }

    @Post("signin")
    @ApiOperation({ summary: "账号密码登录" })
    public async signin(
        @Body() { username, password },
        @Res() res: Response,
        @Ip() ip: string
    ) {
        const user = await this.userService.signup(username, password);
        const token = await this.authService.signToken(user, ip)
        this.authService.setToken(res, token)
        return token;
    }

    // @Get(":id/set")
    // @ApiOperation({ summary: "选择职场" })
    // @UseGuards(AuthGuard("jwt"))
    // public async set(
    //     @Param("id") id: number,
    //     @CurrentUser() user: UserSys,
    //     @Res() res: Response,
    //     @Ip() ip: string
    // ) {
    //     const system = await this.systemService.system.findOne({ where: { id } });
    //     user.system = system;
    //     const token = await this.authService.signToken(user, ip, system);
    //     this.authService.setToken(res, token)
    //     return token;
    // }

    @Get("singout")
    @ApiOperation({ summary: "登出" })
    public async signout(@Res() res: Response) {
        res.clearCookie("token")
        res.send()
    }
}